import {message ,Button,Table, Tabs, Typography, Divider, Popconfirm, DatePicker, Form, Select,notification} from 'antd'
import React, {useState, useRef, useEffect} from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, history } from 'umi'
import { getFundsRecordList, updateRecordStatus, saveMakeUp, deleteFundsRecord, removeAllRecord, removeRecordList,refreshSecurityRecord } from '../service'
import moment from 'moment';
import CreateForm from './components/CreateForm';
import CreateMakeUpForm from "./components/CreateMakeUpForm";
import {getCompanyListAuth} from "@/pages/Security/service";

const  { TabPane } = Tabs;
const { Text } = Typography;
const {Option} = Select;

const TableList = () => {
  const actionRef = useRef();
  const actionRef1 = useRef();
  const actionRef2 = useRef();
  const form = useRef();
  const form2 = useRef();
  const [operationType, setOperationType] = useState('');
  const [visible, setVisible] = useState(false);
  const [makeUpVisible, setMakeUpVisible] = useState(false);
  const [tabIndex, setTabIndex] = useState("0");
  const [remittanceLoading, setRemittanceLoading] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [current, setCurrent] = useState(null);
  const [selectionType, setSelectionType] = useState('checkbox');
  const [selectedRows, setSelectedRows] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [contractData,setContractData] = useState([]);
  const [refreshLoading,setRefreshLoading] = useState(false);
  const [disabled,setDisabled] = useState(false);

  useEffect(() => {
    getCompanyListAuth().then(res => {
      if(res.flag){
        setContractData(res.data);
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
    });
  },[]);

  const rowSelection = {
    onChange: (rowKeys,rows) => {
      setSelectedRows(rows);
    }
  };

  const handleChangTabIndex = (key) => {
    setTabIndex(key)
    if (key==='0'){
      actionRef.current && actionRef.current.reload();
    }else if (key==='1'){
      actionRef1.current && actionRef1.current.reload();
    }else if (key==='3'){
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const remittance = () =>{
    if (selectedRows.length>0){
      setOperationType('remittance');
      setVisible(true);
      setCurrent(selectedRows);
    }else {
      message.info('请选择台账明细！')
    }
  };

  const remittanceAll = () => {
    setRemittanceLoading(true);
    let unitId =form.current.getFieldValue('unitId');
    updateRecordStatus({isAll: 1, status: 0, unitId}).then(res =>{
      if (res.flag){
        message.success('全部汇缴成功！');
        actionRef.current.reload()
      }else{
        message.error(res.error)
      }
      setRemittanceLoading(false);
    });
  };

  const refreshData = () =>{
    let unitId = form.current.getFieldValue('unitId');
    if(!unitId){
      message.error("请先选择汇缴公司！");
      return;
    }
    setRefreshLoading(true);
    setDisabled(true);
    refreshSecurityRecord(unitId,1).then(res =>{
      if (res.flag) {
        message.success('汇缴数据刷新成功！')
        actionRef.current.reload();
      } else {
        message.error(res.error)
      }
      setRefreshLoading(false);
      setDisabled(false);
    })
  };

  const exportAll = () => {
    let unitId =form.current.getFieldValue('unitId');
    let unitName = contractData.find(item => unitId.toString() === item.id.toString()).name;
    window.open(`/hr-ssc/api/api-admin/export/exportFundsRecordAll?unitName=${unitName}&isConfirm=0&isCheck=0`);
  };

  const removeAll = () => {
    let unitId =form.current.getFieldValue('unitId');
    removeAllRecord(unitId).then(res =>{
      if (res.flag){
        message.success('全部删除成功！');
        actionRef.current.reload()
      } else {
        message.error(res.error)
      }
      setConfirmLoading(false);
    });
  };

  const removeList = () => {
    if (selectedRows.length>0){
      removeRecordList(selectedRows.map(item => (item.recordId))).then(res =>{
        if (res.flag){
          message.success('删除成功！');
          actionRef.current.reload()
        } else {
          message.error(res.error)
        }
        setConfirmLoading(false);
      });
    } else {
      message.info('请勾选台账记录！')
    }
  };

  const showMakeUp = (record) =>{
    // setOperationType('makeUp');
    // setVisible(true);
    setMakeUpVisible(true);
    setCurrent([record]);
  };

  const confirmRemittance = () =>{
    if (selectedRows.length>0){
      updateRecordStatus({recordIds: selectedRows.map(item => (item.recordId)), status: 1}).then(res =>{
        if (res.flag){
          message.success('确认成功！');
          actionRef1.current.reload()
        }else{
          message.error(res.error);
        }
      });
    }else {
      message.info('请选择确认项！')
    }
  };

  const confirmRemittanceAll = () =>{
    setConfirmLoading(true);
    let unitId =form2.current.getFieldValue('unitId');
    updateRecordStatus({isAll: 1, status: 1, unitId}).then(res =>{
      if (res.flag){
        message.success('全部确认成功！');
        actionRef.current.reload()
      }else{
        message.error(res.error)
      }
      setConfirmLoading(false);
    });
  };

  const makeUpCancel = ()=>{
    setMakeUpVisible(false);
    setCurrent(null);
  };

  const handleCancel = () => {
    setVisible(false)
  };

  const handleSubmit = (values) =>  {
      updateRecordStatus({recordIds: values.map(item => (item.recordId)), status: 0}).then(res =>{
        setVisible(false);
        setCurrent(null);
        if (res.flag){
          message.success('汇缴成功！');
          actionRef.current.reload()
        }else{
          message.error(res.error);
        }
      });
  };

  const makeUpSubmit = (values,date) => {
    if (date){
     /* let data = {
        oid: values[0].oid,
        time: date,
        type: 1
      };*/
      let data = {
        time: date,
        ...values[0]
      };
      saveMakeUp(data).then(res => {
        setMakeUpVisible(false);
        setCurrent(null);
        if (res.flag){
          message.success('补缴成功！');
          actionRef.current.reload()
        }else{
          message.error(res.error);
        }
      })
    }else {
      message.info('请选择补缴月份！')
    }

  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: '40px',
      align: 'center',
      dataIndex: 'promotionId',
      render:(text,record,index)=>`${index+1}`,
      hideInSearch: true,
    },
    {
      title: '姓名',
      fixed: 'left',
      width: '70px',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '参保地',
      fixed: 'left',
      width: '140px',
      align: 'center',
      dataIndex: 'cityName',
      hideInSearch: true,
    },
    {
      title: '参保单位',
      align: 'center',
      fixed: 'left',
      dataIndex: 'unitName',
      hideInSearch: true
    },
    {
      title: '参保单位',
      dataIndex: 'unitId',
      hideInTable: true,
      renderFormItem: (item, props) => {
        return <Select placeholder="请选择参保单位" showSearch filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
          { contractData.length>0 ? contractData.map((item, index) => {
            return (
              <Option value={item.id} key={index} lable={item}>
                {item.name}
              </Option>
            )
          }) : ''}
        </Select>;
      },
    },
    {
      title: '缴费时间',
      dataIndex: 'operateTime',
      hideInSearch: tabIndex !== '3',
      renderFormItem: (item, props) => {
        return <DatePicker {...props} picker="month" />;
      },
      render: (text) => {
        return text!=='-'?moment(text).format('YYYY-MM'):''
      }
    },
    {
      title: '公积金',
      children: [
        {
          title: '基数',
          dataIndex: 'reservedFundsBase',
          hideInSearch: true,
        },
        {
          title: '个人',
          children: [
            {
              title: '缴纳',
              dataIndex: 'reservedFundsPerson',
              hideInSearch: true,
            },
            {
              title: '比例',
              dataIndex: 'reservedFundsPersonRate',
              hideInSearch: true,
              render: (text) => {
                return text?`${text}%`:text
              }
            },
          ]
        },
        {
          title: '公司',
          children: [
            {
              title: '缴纳',
              dataIndex: 'reservedFundsOrg',
              hideInSearch: true,
            },
            {
              title: '比例',
              dataIndex: 'reservedFundsOrgRate',
              hideInSearch: true,
              render: (text) => {
                return text?`${text}%`:text
              }
            },
          ]
        }
      ]
    },
    {
      title: '补充公积金',
      children: [
        {
          title: '基数',
          dataIndex: 'offerFundsBase',
          hideInSearch: true,
        },
        {
          title: '个人',
          children: [
            {
              title: '缴纳',
              dataIndex: 'offerFundsPerson',
              hideInSearch: true,
            },
            {
              title: '比例',
              dataIndex: 'offerFundsPersonRate',
              hideInSearch: true,
              render: (text) => {
                return text?`${text}%`:text
              }
            },
          ]
        },
        {
          title: '公司',
          children: [
            {
              title: '缴纳',
              dataIndex: 'offerFundsOrg',
              hideInSearch: true,
            },
            {
              title: '比例',
              dataIndex: 'offerFundsOrgRate',
              hideInSearch: true,
              render: (text) => {
                return text?`${text}%`:text
              }
            },
          ]
        }
      ]
    },

    {
      title: '合计',
      children: [
        {
          title: '个人',
          dataIndex: 'personCostTotal',
          hideInSearch: true,
        },
        {
          title: '公司',
          dataIndex: 'orgCostTotal',
          hideInSearch: true,
        },
      ]
    },
    {
      title: '操作',
      align: 'center',
      width: 100,
      dataIndex: 'option',
      valueType: 'option',
      hideInTable: tabIndex === '3',
      render: (item, record) => (
        <>
          <a onClick={() => showMakeUp(record)}>补缴</a>
          <Divider type="vertical"/>
          <Popconfirm title={`是否确认删除?`}
                      onConfirm={() => deleteLedger(record.recordId)}
                      okText="是" cancelText="否">
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const deleteLedger = (recordId) => {
    deleteFundsRecord(recordId).then(res => {
      if (res.flag){
        message.success('台账删除成功');
      }else {
        message.error(res.error);
      }
      if (tabIndex==='0'){
        actionRef.current && actionRef.current.reload();
      }else if (tabIndex==='1'){
        actionRef1.current && actionRef1.current.reload();
      }
    })
  };

  const setTotalRow = () => {
    let sumObj = {
      reservedFundsPersonSum: 0,
      reservedFundsOrgSum: 0,
      offerFundsPersonSum: 0,
      offerFundsOrgSum: 0,
      personCostTotalSum: 0,
      orgCostTotalSum: 0,
    };
    tableData?.forEach(({reservedFundsPerson, reservedFundsOrg, offerFundsPerson,
                            offerFundsOrg, personCostTotal, orgCostTotal}) => {
      sumObj.reservedFundsPersonSum += reservedFundsPerson;
      sumObj.reservedFundsOrgSum += reservedFundsOrg;
      sumObj.offerFundsPersonSum += offerFundsPerson;
      sumObj.offerFundsOrgSum += offerFundsOrg;
      sumObj.personCostTotalSum += personCostTotal;
      sumObj.orgCostTotalSum += orgCostTotal;
    });

    return (
      <>
        <Table.Summary.Row >
          <Table.Summary.Cell colSpan={tabIndex!=='3' ? 5 : 4} index={0} className='textCenter'>小计</Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.reservedFundsPersonSum.toFixed(2)}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.reservedFundsOrgSum.toFixed(2)}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.offerFundsPersonSum.toFixed(2)}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.offerFundsOrgSum.toFixed(2)}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={tabIndex!=='3' ? 40 : 39} />
          <Table.Summary.Cell index={tabIndex!=='3' ? 41 : 40}>
            <Text>{sumObj.personCostTotalSum.toFixed(2)}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={tabIndex!=='3' ? 42 : 41}>
            <Text>{sumObj.orgCostTotalSum.toFixed(2)}</Text>
          </Table.Summary.Cell>
          { tabIndex!=='3' && <Table.Summary.Cell index={43} />}
        </Table.Summary.Row>
      </>
    );
  };

  return (
    <PageHeaderWrapper>
      {
        contractData.length >0 &&
        <Tabs animated={false} defaultActiveKey="0" onChange={handleChangTabIndex}>
          <TabPane tab="未汇缴" key="0" disabled={disabled}>
            <ProTable
              loading={disabled}
              bordered
              actionRef={actionRef}
              form={{initialValues: {unitId: contractData[0].id}}}
              formRef={form}
              rowKey="recordId"
              rowSelection={{
                type: selectionType,
                ...rowSelection,
              }}
              request={(params) => getFundsRecordList(params,0,0).then(res=>{
                setTableData(res.data);
                return res;
              })}
              onReset={()=> {form.current.setFieldsValue({unitId: contractData[0].id})}}
              columns={columns}
              toolBarRender={(action, { selectedRows }) => [
                // 老蔡要求先注释该功能，因为刷新方案会先执行删除当前月数据  czw 2021-04-07
                // <Popconfirm
                //   title="此操作将删除当前方案下台账所有记录，是否确认操作？"
                //   onConfirm={removeAll}
                //   okText="确认"
                //   cancelText="取消"
                // >
                //   <Button key='0'>全部删除</Button>
                // </Popconfirm>,
                <Popconfirm
                  title="此操作将删勾选的台账所有记录，是否确认操作？"
                  onConfirm={removeList}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button key='1'>选择删除</Button>
                </Popconfirm>,
                <Popconfirm
                  title="此操作将导出本次汇缴期所选单位的全部数据，是否确认操作？"
                  onConfirm={exportAll}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button key='2' type="primary">全部导出</Button>
                </Popconfirm>,
                <Popconfirm
                  title="此操作会将当前筛选缴纳单位中的所有数据进行汇缴，是否确认操作？"
                  onConfirm={remittanceAll}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button key='3' loading={remittanceLoading} type="primary">全部汇缴</Button>
                </Popconfirm>,
                // 奇葩用户太多，老蔡要求注释 czw 2021-04-09
                // <Button type="primary" onClick={() => remittance()}>选择汇缴</Button>,
                <Popconfirm
                  title="此操作将会重新计算汇缴数据，是否确认操作？"
                  onConfirm={refreshData}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button key='4' danger loading={refreshLoading}>刷新台账</Button>
                </Popconfirm>,
              ]}
              summary={setTotalRow}
              pagination={{pageSizeOptions:['20', '50', '100', '200', '500']}}
            />
          </TabPane>
          <TabPane tab="已汇缴" key="1" disabled={disabled}>
              <ProTable
                bordered
                actionRef={actionRef1}
                formRef={form2}
                form={{initialValues: {unitId: contractData[0].id}}}
                rowKey="recordId"
                request={(params) => getFundsRecordList(params,0,1).then(res=>{
                  setTableData(res.data);
                  return res;
                })}
                onReset={()=> {form2.current.setFieldsValue({unitName: contractData[0].name})}}
                columns={columns}
                rowSelection={{
                  type: selectionType,
                  ...rowSelection,
                }}
                toolBarRender={(action, { selectedRows }) => [
                  <Popconfirm
                    title="此操作会将当前筛选缴纳单位中的所有数据进行确认，是否确认操作？"
                    onConfirm={confirmRemittanceAll}
                    okText="确认"
                    cancelText="取消"
                  >
                    <Button key='button' loading={confirmLoading} type="primary">确认汇缴</Button>
                  </Popconfirm>,
                  // 奇葩用户太多，老蔡要求注释 czw 2021-04-09
                  // <Button type="primary" onClick={() => confirmRemittance()}>选择确认</Button>
                ]}
                summary={setTotalRow}
                pagination={{pageSizeOptions:['20', '50', '100', '200', '500']}}
              />
          </TabPane>
          <TabPane tab="已确认" key="3" disabled={disabled}>
            <ProTable
              bordered
              actionRef={actionRef2}
              rowKey="recordId"
              request={(params) => getFundsRecordList(params,1).then(res=>{
                setTableData(res.data);
                return res;
              })}
              columns={columns}
              summary={setTotalRow}
              pagination={{pageSizeOptions:['20', '50', '100', '200', '500']}}
            />
          </TabPane>
        </Tabs>
      }

      <CreateForm
        operationType={operationType}
        current={current}
        visible={visible}
        makeUpSubmit={makeUpSubmit}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />

      <CreateMakeUpForm
        visible={makeUpVisible}
        current={current}
        makeUpSubmit={makeUpSubmit}
        onCancel={makeUpCancel}
      />

    </PageHeaderWrapper>
  )
};

export default connect(({  }) => ({
}))(TableList)
